﻿var ajaxHelper = {};

ajaxHelper.const = {
    containerId: "ajax_model_container"
};

ajaxHelper.showDialog = function (data) {
    var $container = $("#" + ajaxHelper.const .containerId);
    var $form = $(ajaxHelper.const.containerId + " form");
    $container.html(data);
    $form.removeData("validator").removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse($form);
    $container.modal();
};

ajaxHelper.reload = function (data) {
    if (data == "OK") {
        $("#" + ajaxHelper.const.containerId).modal("hide");
        $(".form-search form").submit();
    }
};

ajaxHelper.onSelectChange = function (data, that) {
    if (!that.value) return;

    var $that = $(that);
    $.post($that.attr("url"), { param: that.value }, function (json) {
        var $options;
        var $target = $("#" + $that.attr("update-id"));
        $.each(json, function (i, item) {
            var $option = $("<option></option>").val(item.Value).text(item.Text);
            if (!$options) {
                $options = $option;
                return true;
            }
            $options = $options.after($option);
        });
        $target.html($options);
        if ($target.attr("data-ajax")) {
            $target.trigger("change");
        }
    });
};

$(function () {
    var $ajaxDropDown = $("select[data-ajax='true']");
    $ajaxDropDown.live("change", function (data) {
        ajaxHelper.onSelectChange(data, this);
    });
    $ajaxDropDown.trigger("change");
});